<?php

namespace App\Http\Controllers;

use App\Models\Address;
use Illuminate\Http\Request;

class AddressController extends Controller
{
    public function index(Request $request)
    {
        $data = Address::where('user_id', $request->user()->id)->orderBy('status', 'desc')->get();
        return $this->response($data);
    }

    public function view($id)
    {
        $obj = Address::find($id);
        return $this->response($obj);
    }

    public function store(Request $request, Address $obj)
    {
        $all = $request->all();
        $obj->fill($all);
        $obj->user_id = $request->user()->id;
        if ($obj->status == 1) {
            Address::updateAllStatus($request->user()->id);
        }
        $obj->save();
        return $this->response($obj->id);
    }

    public function update($id, Request $request)
    {
        $obj = Address::find($id);
        $data = $request->all();
        if ($data['status'] == 1) {
            Address::updateAllStatus($request->user()->id);
        }
        $obj->update($data);
        return $this->response($obj->id);
    }

    public function destroy($id)
    {
        $obj = Address::find($id);
        $obj->delete();
        return $this->response();
    }
}
